<template>
  <div style="width: 400px;text-align:center;margin: 0 auto">
    <h1>{{ msg }}</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          type="text"
          v-model="ruleForm.userName"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="pass" style="margin-bottom: 40px;">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="ruleForm.confirmPassword"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="cellPhoneNumber">
        <el-input
          type="text"
          v-model="ruleForm.cellPhoneNumber"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <div class="code-box" v-show="isCountFormShow">
        <el-form-item prop="verificationCode">
          <el-input
            placeholder="短信验证码"
            v-model="ruleForm.verificationCode"
          ></el-input>
        </el-form-item>
        <span class="code-img">
          <el-button
            @click="getCode"
            type="primary"
            plain
            :disabled="isDisabled"
            >{{
              isDisabled ? countText.count + "s后获取" : countText.click
            }}</el-button
          >
        </span>
      </div>

      <el-form-item>
        <el-button-group style="margin-bottom:20px">
          <el-button size="small" type="primary" @click="submitForm('ruleForm')"
            >重设密码</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {validatePhone,validateEmail} from "../utils/pubfun";
import request from "../utils/request";
export default {
  name: "UserRegister",
  data() {
    const validateUser = (rule, value, callback) => {
      //debugger;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      // debugger;
      let reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~@#$%\*-\+=:,\\?\[\]\{}]).{6,16}$/;
      if (value.length < 6) {
        return callback(new Error("密码不能少于6位！"));
      } else if (value.length > 16) {
        return callback(new Error("密码最长不能超过16位！"));
      } else if (!reg.test(value)) {
        return callback(
          new Error(
            "密码有误，6-16位字符，同时包括数字、大小写字母和特殊字符四种组合； 特殊字符需在“~ @ # $ % * _ - + = : , . ?”范围内选择!"
          )
        );
      } else {
        callback();
      }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value.length < 1) {
        return callback(new Error("确认密码不能为空！"));
      } else if (this.ruleForm.pass != this.ruleForm.confirmPassword) {
        return callback(new Error("两次输入密码不一致！"));
      } else {
        callback();
      }
    };
    const validateCellPhoneNumber = (rule, value, callback) => {
      let errMsg = validatePhone(value);
      if (errMsg != "") {
        callback(new Error(errMsg));
      } else {
        this.isCountFormShow = true;
        callback();
      }
    };
    const verificationCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入短信验证码"));
      } else {
        callback();
      }
    };
    return {
      msg: "重设用户密码",
      ruleForm: {
        userName: "",
        pass: "",
        confirmPassword: "",
        verificationCode: "",
        cellPhoneNumber: "",
        email: ""
      },
      rules: {
        userName: [
          {validator: validateUser, trigger: "blur"}
        ],
        pass: [
          { validator: validatePass, trigger: "blur" }
        ],
        confirmPasswordPass: [
          {
            validator: validateConfirmPassword,
            trigger: "blur"
          }
        ],
        cellPhoneNumber: [
          {
            required: true,
            validator: validateCellPhoneNumber,
            trigger: "blur"
          }
        ],
         verificationCode: [
          { required: true, validator: verificationCode, trigger: "blur" }
        ]
      },
      countText: {
        count: "59",
        click: "获取短信"
      },
      isCountFormShow: false,
      isDisabled: false
    };
  },
  methods: {
    // 倒计时
    countTime() {
      const TIME_COUNT = 60; //倒计时60秒
      if (!this.timer) {
        this.countText.count = TIME_COUNT;
        this.isDisabled = true;
        this.timer = setInterval(() => {
          if (this.countText.count > 0 && this.countText.count <= TIME_COUNT) {
            this.countText.count--;
          } else {
            this.isDisabled = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 点击获取短信验证码
    getCode() {
      var _this = this;

      //发送验证码
      request({
        method: "POST",
        url: "/api/sms/sendSmsVerifyCode?mobilePhone="+_this.ruleForm.cellPhoneNumber
      })
        .then(res => {
          if (res.data.status == "1") {
            _this.countTime();
          } else {
            _this.$message(res.data.message);
            return false;
          }
        })
        .catch(err => {
          console.log(err);
          _this.$message("发送短信失败!");
        });
    },

    submitForm(formName) {
      let _this = this;
      const param = {
        userName: _this.ruleForm.userName,
        password: _this.ruleForm.pass,
        verificationCode: _this.ruleForm.verificationCode,
        cellPhoneNumber: _this.ruleForm.cellPhoneNumber
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            method: "POST",
            url: "/api/User/resetPassword",
            data: param
          })
            .then(res => {
              if (res.data.status == "1") {
                _this.$message(res.data.message);
                _this.$router.push({ path: "/login" });
              } else {
                _this.$message(res.data.message);
                return false;
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.code-box {
  display: flex;
  font-size: 14px;
}

.my-input {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  background: rgba(0, 0, 0, 0);
  padding: 0 10px;
  font-size: 16px;
}

.my-input-code {
  width: 100px !important;
}

.code-img {
  flex: 4;
  height: 40px;
  line-height: 40px;
  display: inline-block;
  border-radius: 4px;
  box-sizing: border-box;
  outline: 0;
  margin-left: 10px;
  overflow: hidden;
}


</style>
